#include "FacebookUtils.h"
#include <FacebookSDK/FacebookSDK.h>
#include "AppController.h"

void FacebookUtils::setAdInvisible(bool isInvisible) {
    AppController *appController = (AppController *)[UIApplication sharedApplication].delegate;
    
    if (isInvisible) {
        [appController setAdVisible:YES];
    } else {
        [appController setAdVisible:NO];
    }
}

void FacebookUtils::share(char* name, char* caption, char* description, char* link, char* picture, CCMenuItemSprite* button) {
    NSString* nsName = [NSString stringWithUTF8String:name];
    NSString* nsCaption = [NSString stringWithUTF8String:caption];
    NSString* nsDescription = [NSString stringWithUTF8String:description];
    NSString* nsLink = [NSString stringWithUTF8String:link];
    NSString* nsPicture = [NSString stringWithUTF8String:picture];
    
    // Put together the dialog parameters
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys: nsName,
                                   @"name", nsCaption,
                                   @"caption", nsDescription,
                                   @"description", nsLink,
                                   @"link", nsPicture,
                                   @"picture",
                                   nil];
    
    // Invoke the dialog
    [FBWebDialogs presentFeedDialogModallyWithSession:nil
                                        parameters:params
                                        handler:
     ^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
        if (error) {
            // Error launching the dialog or publishing a story.
            NSLog(@"Error publishing story.");
        } else {
            if (result == FBWebDialogResultDialogNotCompleted) {
                // User clicked the "x" icon
                NSLog(@"User canceled story publishing.");
            } else {
                [[[UIAlertView alloc] initWithTitle:@"Result"
                                                message:@"Đã chia sẻ"
                                                delegate:nil
                                                cancelButtonTitle:@"OK!"
                                                otherButtonTitles:nil] show];
            }
        }
         button->setEnabled(true);
     }];
}

bool FacebookUtils::isLoggedFacebook() {
    if (FBSession.activeSession.state == FBSessionStateOpen) {
        return true;
    }
    if (FBSession.activeSession.state == FBSessionStateCreatedTokenLoaded) {
        authenticate();
        return true;
    }
    return false;
}

void FacebookUtils::authenticate() {
    FBSession* facebookSession = [FBSession activeSession];
    if (facebookSession.state == FBSessionStateClosedLoginFailed) {
        return;
    }
    
    if (facebookSession.state != FBSessionStateCreated) {
        facebookSession = [[FBSession alloc] init];
    }
    
    [FBSession.activeSession openWithCompletionHandler:^(FBSession *session,
                                                     FBSessionState status,
                                                     NSError *error) {
    }];
    //[FBSession openActiveSessionWithAllowLoginUI:true];
}

void FacebookUtils::askFriend(char* askType, char* requestType, char* message, char* caption) {
    NSString* nsAskType = [NSString stringWithUTF8String:askType];
    NSString* nsRequestType = [NSString stringWithUTF8String:requestType];
    NSString* nsMessage = [NSString stringWithUTF8String:message];
    NSString* nsCaption = [NSString stringWithUTF8String:caption];
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization
                        dataWithJSONObject:@{
                                             @"requestType": nsRequestType,
                                             @"askType": nsAskType}
                        options:0
                        error:&error];
    if (!jsonData) {
        NSLog(@"JSON error: %@", error);
        return;
    }
    
    NSString *reqStr = [[NSString alloc]
                         initWithData:jsonData
                         encoding:NSUTF8StringEncoding];
    
    NSMutableDictionary* params = [@{@"data" : reqStr} mutableCopy];
    
    // Display the requests dialog
    [FBWebDialogs
     presentRequestsDialogModallyWithSession:nil
     message:nsMessage
     title:nsCaption
     parameters:params
     handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
         if (error) {
             // Error launching the dialog or sending the request.
             NSLog(@"Error sending request.");
         } else {
             if (result == FBWebDialogResultDialogNotCompleted) {
                 // User clicked the "x" icon
                 NSLog(@"User canceled request.");
             } else {
                 // Handle the send request callback
                 NSArray *pairs = [[resultURL query] componentsSeparatedByString:@"&"];
                 NSMutableDictionary *urlParams = [[NSMutableDictionary alloc] init];
                 for (NSString *pair in pairs) {
                     NSArray *kv = [pair componentsSeparatedByString:@"="];
                     NSString *val =
                     [kv[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                     urlParams[kv[0]] = val;
                 }
                 
                 if (![urlParams valueForKey:@"request"]) {
                     // User clicked the Cancel button
                     NSLog(@"User canceled request.");
                 } else {
                     // User clicked the Send button
                     NSString *requestID = [urlParams valueForKey:@"request"];
                     NSLog(@"Request ID: %@", requestID);
                 }
             }
         }
     }];
}

void FacebookUtils::sendRequestToRecipent(char* to, char* askType, char* requestType, char* message, char* caption) {
    NSString* nsTo = [NSString stringWithUTF8String:to];
    NSString* nsAskType = [NSString stringWithUTF8String:askType];
    NSString* nsRequestType = [NSString stringWithUTF8String:requestType];
    NSString* nsMessage = [NSString stringWithUTF8String:message];
    NSString* nsCaption = [NSString stringWithUTF8String:caption];
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization
                        dataWithJSONObject:@{
                                             @"requestType": nsRequestType,
                                             @"askType": nsAskType}
                        options:0
                        error:&error];
    if (!jsonData) {
        NSLog(@"JSON error: %@", error);
        return;
    }
    
    NSString *reqStr = [[NSString alloc]
                        initWithData:jsonData
                        encoding:NSUTF8StringEncoding];
    

    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys: @"1396105833971269",
                                   @"app_id", nsTo,
                                   @"to", reqStr,
                                   @"data", nil];

    [FBWebDialogs
     presentRequestsDialogModallyWithSession:nil
     message:nsMessage
     title:nsCaption
     parameters:params
     handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
         if (error) {
             // Error launching the dialog or sending the request.
             NSLog(@"Error sending request.");
         } else {
             if (result == FBWebDialogResultDialogNotCompleted) {
                 // User clicked the "x" icon
                 NSLog(@"User canceled request.");
             } else {
                 // Handle the send request callback
                 NSArray *pairs = [[resultURL query] componentsSeparatedByString:@"&"];
                 NSMutableDictionary *urlParams = [[NSMutableDictionary alloc] init];
                 for (NSString *pair in pairs) {
                     NSArray *kv = [pair componentsSeparatedByString:@"="];
                     NSString *val =
                     [kv[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                     urlParams[kv[0]] = val;
                 }
                 
                 if (![urlParams valueForKey:@"request"]) {
                     // User clicked the Cancel button
                     NSLog(@"User canceled request.");
                 } else {
                     // User clicked the Send button
                     NSString *requestID = [urlParams valueForKey:@"request"];
                     NSLog(@"Request ID: %@", requestID);
                 }
             }
         }
     }];
}

void FacebookUtils::getFacebookUserId(CCArray* collectedUserId) {
    if (isLoggedFacebook()) {
        [FBRequestConnection startWithGraphPath:@"me?fields=id,last_name"
                              completionHandler:^(FBRequestConnection *connection,
                                                  id result,
                                                  NSError *error) {
                                  if (!error) {
                                      FBGraphObject* fbGraphObject = (FBGraphObject *) result;
                                      const char* userId = [[NSString stringWithFormat:@"%@", fbGraphObject[@"id"]] cStringUsingEncoding:NSUTF8StringEncoding];
                                      const char* name = [[NSString stringWithFormat:@"%@", fbGraphObject[@"last_name"]] cStringUsingEncoding:NSUTF8StringEncoding];
                                      CCDictionary* dict = CCDictionary::create();
                                      dict->setObject(CCString::create(name), userId);
                                      collectedUserId->addObject(dict);
                                  }
                              }];
    }
}

void FacebookUtils::getFriendList(CCArray* friendList) {
    if (isLoggedFacebook()) {
        [FBRequestConnection startWithGraphPath:@"me/friends?fields=installed,last_name"
                              completionHandler:^(FBRequestConnection *connection,
                                                  id result,
                                                  NSError *error) {
                                  if (!error) {
                                      FBGraphObject* fbGraphObject = (FBGraphObject *) result;
                                      NSMutableArray* friendArray = fbGraphObject[@"data"];
                                      for (FBGraphObject* friendObj in friendArray) {
                                          if (friendObj[@"installed"] != NULL)  {
                                              const char* friendId = [[NSString stringWithFormat:@"%@", friendObj[@"id"]] cStringUsingEncoding:NSUTF8StringEncoding];
                                              const char* friendName = [[NSString stringWithFormat:@"%@", friendObj[@"last_name"]] cStringUsingEncoding:NSUTF8StringEncoding];
                                              
                                              CCDictionary* dict = CCDictionary::create();
                                              dict->setObject(CCString::create(friendName), friendId);
                                              friendList->addObject(dict);
                                          }
                                      }
                                  }
                              }];
    }

}

void FacebookUtils::getAllRequest(CCArray* requestsObtained) {
    if (isLoggedFacebook()) {
        [FBRequestConnection startWithGraphPath:@"me/apprequests"
                          completionHandler:^(FBRequestConnection *connection,
                                              id result,
                                              NSError *error) {
                              if (!error) {
                                  FBGraphObject* fbGraphObject = (FBGraphObject *) result;
                                  NSMutableArray* requestArray = fbGraphObject[@"data"];
                                  for (FBGraphObject* request in requestArray) {
                                      const char* requestId = [[NSString stringWithFormat:@"%@", request[@"id"]] cStringUsingEncoding:NSUTF8StringEncoding];
                                      const char* from = [[NSString stringWithFormat:@"%@", request[@"from"][@"name"]] cStringUsingEncoding:NSUTF8StringEncoding];
                                      const char* fromId = [[NSString stringWithFormat:@"%@", request[@"from"][@"id"]] cStringUsingEncoding:NSUTF8StringEncoding];
                                      const char* to = [[NSString stringWithFormat:@"%@", request[@"to"][@"name"]] cStringUsingEncoding:NSUTF8StringEncoding];
                                      NSString* jsonString = request[@"data"];
                                      NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
                                      if (!jsonData) {
                                          NSLog(@"JSON decode error: %@", error);
                                          continue;
                                      }
                                      NSError *jsonError = nil;
                                      NSDictionary *requestData =
                                      [NSJSONSerialization JSONObjectWithData:jsonData
                                                                      options:0
                                                                        error:&jsonError];
                                      if (jsonError) {
                                          NSLog(@"JSON decode error: %@", error);
                                          continue;
                                      }
                                      
                                      const char* requestType = [[NSString stringWithFormat:@"%@", requestData[@"requestType"]] cStringUsingEncoding:NSUTF8StringEncoding];
                                      const char* askType = [[NSString stringWithFormat:@"%@", requestData[@"askType"]] cStringUsingEncoding:NSUTF8StringEncoding];
                                      
                                      CCDictionary* dictionary = CCDictionary::create();
                                      dictionary->setObject(CCString::create(requestId), "requestId");
                                      dictionary->setObject(CCString::create(from), "from");
                                      dictionary->setObject(CCString::create(fromId), "fromId");
                                      dictionary->setObject(CCString::create(to), "to");
                                      dictionary->setObject(CCString::create(requestType), "requestType");
                                      dictionary->setObject(CCString::create(askType), "askType");
                                      
                                      requestsObtained->addObject(dictionary);
                                  }
                              }
                          }];
    }
}

void FacebookUtils::deleteRequest(const char* requestId) {
    NSString* nsRequestId = [NSString stringWithUTF8String:requestId];
    [FBRequestConnection startWithGraphPath:nsRequestId
                                 parameters:nil
                                 HTTPMethod:@"DELETE"
                          completionHandler:^(FBRequestConnection *connection,
                                              id result,
                                              NSError *error) {
                              if (!error) {
                                  NSLog(@"Request deleted");
                              }
                          }];
}

void FacebookUtils::getImage(char* link, CCSprite* sprite) {
    /*NSString *imgAdd = [NSString stringWithUTF8String:link];
    NSURL *imgUrl = [NSURL URLWithString:imgAdd];
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imgUrl]];

    CCImage *imf = new CCImage();
    NSData *imgData = UIImagePNGRepresentation(image);
    NSUInteger len = [imgData length];
    Byte *byteData = (Byte*)malloc(len);
    memcpy(byteData, [imgData bytes], len);
    imf->initWithImageData(byteData,imgData.length);
    imf->autorelease();
    CCTexture2D* pTexture = new CCTexture2D();
    pTexture->initWithImage(imf);
    pTexture->autorelease();
    sprite->initWithTexture(pTexture);*/
}

void FacebookUtils::loadImage(char *link, char* name, CCDictionary* cache) {
    NSString* nsLink = [NSString stringWithUTF8String:link];
    NSURL* nsUrl = [NSURL URLWithString:nsLink];
    const NSString* nsName = [NSString stringWithUTF8String:name];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:nsUrl];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               if ( !error )
                               {
                                   UIImage *image = [[UIImage alloc] initWithData:data];
                                   CCImage *imf = new CCImage();
                                   NSData *imgData = UIImagePNGRepresentation(image);
                                   NSUInteger len = [imgData length];
                                   Byte *byteData = (Byte*)malloc(len);
                                   memcpy(byteData, [imgData bytes], len);
                                   imf->initWithImageData(byteData,imgData.length);
                                   imf->autorelease();
                                   CCTexture2D* pTexture = new CCTexture2D();
                                   pTexture->initWithImage(imf);
                                   pTexture->autorelease();
                                   const char* keyName = [nsName cStringUsingEncoding:NSUTF8StringEncoding];
                                   cache->setObject(pTexture, keyName);
                               }
                           }];
}

void FacebookUtils::showDialog(char* titleStr, char* contentStr, char* doneTextStr) {
    NSString* title = [NSString stringWithUTF8String:titleStr];
    NSString* content = [NSString stringWithUTF8String:contentStr];
    NSString* doneText = [NSString stringWithUTF8String:doneTextStr];
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:title
                          message:content
                          delegate:nil
                          cancelButtonTitle:doneText
                          otherButtonTitles:nil,
                          nil];
    [alert show];
}

void FacebookUtils::openMessage(char* messageContent, char* number) {
    NSString* nsNumber = [NSString stringWithFormat:@"sms:+%s", number];
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = [NSString stringWithUTF8String:messageContent];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:nsNumber]];
//    if([MFMessageComposeViewController canSendText]) {
//        MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
//        controller.body = @"Hello";
//        controller.recipients = [NSArray arrayWithObjects:@"+1234567890", nil];
//        controller.messageComposeDelegate = (id<MFMessageComposeViewControllerDelegate>) [UIApplication sharedApplication].keyWindow.rootViewController;
//        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:controller animated:YES completion:nil];
//    }
}

bool FacebookUtils::isiPad() {
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        return true;
    }
    return false;
}

std::string FacebookUtils::getDeviceId() {
    NSUUID* strUniqueIdentifier = [[UIDevice currentDevice] identifierForVendor];
    const char* uuidChar = [[strUniqueIdentifier UUIDString] cStringUsingEncoding:NSUTF8StringEncoding];
    return uuidChar;
}
